#!usr/bin/env python3
# -*- coding: utf8 -*-

#，配置表字段名二进制保存demo
import math
import struct
from io import StringIO,BytesIO
import uuid,os,time

#把配置obj转换成二进制字段名保存数据
def objToBinArr(obj,fields:list):
    ret = -1    
    extKeys = []
    values = []
    for idx in range(0,len(fields)):
        key = fields[idx]
        if key in obj and obj[key]:
            sub = 1<<idx
            print("sub",sub,bin(sub),"idx",idx)
            if ret==-1:
                ret = sub
            else:                
                ret = ret | sub
            extKeys.append(key)
            values.append(obj[key])
            
    #print("extKeys",extKeys,"fields",fields,"ret",ret,bin(ret))
    print("--------------------- ret",bin(ret))
    return [ret]+values

#把二进制字段名保存数据转换成obj
def binDataToObj(arr:list,fields:list):
    retObj = {}    
    pKey = arr[0]
    stIdx = 1
    for idx in range(0,len(fields)):
        sub = 1<<idx & pKey
        if sub>0:
            key = fields[idx]
            retObj[key] = arr[stIdx]
            stIdx+=1
    return retObj

fields = ["code", "levelimit", "reward", "broadcast","copyType","name"]
#fields = ["code", "copyType", "enterMaxLevel", "enterMinLevel", "enterMinRoleState", "enterMaxRoleState", "intoMapId", "introduction", "isAssist", "maps", "name", "numByDay", "reward", "showLeave", "singleMode", "stayTime", "waitLeaveSec", "sucessLeaveSec", "failLeaveSec", "singlePickup", "needProp", "propNum", "warfare", "chatCross"]
#fields = ["bind", "career", "careerMap", "category", "code", "codeUnbind", "color", "credit", "dayUseNum", "defaultUseNum", "descStr", "descStr2", "effect", "effectEx", "effectEx2", "effectTime", "existDay", "expand", "extendStr", "gainDesc", "icon", "itemFlag", "itemLevel", "level", "lotteryEffect", "name", "overlay", "petExp", "quickUseTip", "sell", "sellPrice", "sellUnit", "shape", "shortName", "showEffect", "strengthenEx", "type", "usageDesc", "useFlag", "useType"]
    
fields.sort()
print("************************************************************ +++++++++++++++++ fields len",len(fields))
datas = [
    {"name":"kfz1","copyType":21,"reward":"1,2,3,4","enterMaxLevel":0},
    {"name":"kfz2","copyType":22,"enterMaxLevel":12},
    {"name":"kfz3","copyType":23,"broadcast":"这是广播"},
    {"name":"kfz3","copyType":23,"broadcast":"这是广播","enterMaxLevel":10,"reward":"1,2,3,4,5"}
]

results = []

for v in datas:
    rets = objToBinArr(v,fields)
    if len(rets)>0:        
        results.append(rets)

print("results",results)

jsonDatas = []
for v in results:
    retObj = binDataToObj(v,fields)
    jsonDatas.append(retObj)

print("jsonDatas",jsonDatas)


def encode(s):
    return "".join([hex(ord(c)^0xff) for c in s])

def decode(s):
    s = s.split("0x")
    print("decode",s)
    s = "".join([chr((int('0x'+c,16)^0xff)) for c in s if c])
    print("s",s)
    return s

def witeByte(s):
    s = s.split("0x")
    data = [ int("0x"+c,16) for c in s if c]
    byte = bytes(data)
    with open("my.bin","wb") as f:
        f.write(byte)

def readByteToStr():
    byt = None
    with open("my.bin","rb") as f:
        byt = f.read()
    ret = ""
    for i in range(0,len(byt)):        
        ret+=hex(byt[i])

    return ret

s = "98f02970761b11e986043497f6389fcb"


bys = encode(s)
print("bys",bys)
#witeByte(bys)
ret = readByteToStr()
ret = decode(ret)
print("s==ret",s==ret,"ret",ret)



